package com.ben.multiple.elasticsearch.resource;

import com.ben.multiple.elasticsearch.DateUtils;
import org.springframework.data.elasticsearch.core.convert.AbstractPropertyValueConverter;
import org.springframework.data.elasticsearch.core.convert.ConversionException;
import org.springframework.data.mapping.PersistentProperty;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author ben
 */
public class LocalDateTimePropertyValueConverter extends AbstractPropertyValueConverter {
    static DateTimeFormatter localDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    static DateTimeFormatter localDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public LocalDateTimePropertyValueConverter(PersistentProperty<?> property) {
        super(property);
    }

    @Override
    public Object read(Object value) {
        if (value == null) {
            return null;
        }
        String s = value.toString();
        Class<?> actualType = getProperty().getActualType();
        if (actualType == LocalDateTime.class) {
            return DateUtils.parseToLocalDateTime(s);
        } else if (actualType == LocalDate.class) {
            return DateUtils.parseToLocalDate(s);
        } else {
            throw new ConversionException(String.format("Unable to convert value '%s' to %s for property '%s'", value,
                    getProperty().getActualType().getTypeName(), getProperty().getName()));
        }
    }

    @Override
    public Object write(Object value) {
        if (value == null) {
            return null;
        }
        Class<?> actualType = getProperty().getActualType();
        if (actualType == LocalDateTime.class) {
            return ((LocalDateTime) value).format(localDateTimeFormatter);
        } else if (actualType == LocalDate.class) {
            return ((LocalDate) value).format(localDateFormatter);
        } else {
            return null;
        }
    }

}
